<template>
    <dept-dialog class="deptForm" :title="props.title" :show="props.show" @close="close" @submit="submit">
        <el-form :model="deptData" :rules="rules" ref="deptForm" label-width="100">
            <el-form-item label="上级部门" prop="parentId" required>
                <el-cascader v-model="deptData.parentId" :options="props.dept" clearable
                    :props="{checkStrictly:true,value:'id',label:'deptName'}" show-all-levels>
                </el-cascader>
            </el-form-item>
            <el-form-item label="部门名称" prop="deptName" required>
                <el-input v-model="deptData.deptName" placeholder="请输入部门名称"></el-input>
            </el-form-item>
            <el-form-item label="负责人" prop="user" required>
                <el-select @change="handleUser" ref="roleSelect" v-model="deptData.user" v-loadmore="loadMore">
                    <el-option v-for="item in list" :value="`${item.userId}/${item.userName}/${item.userEmail}`"
                        :key="item.userId" :label="item.userName"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="负责人邮箱" prop="userEmail">
                <el-input disabled v-model="deptData.userEmail" placeholder="请输入负责人邮箱"></el-input>
            </el-form-item>
        </el-form>
    </dept-dialog>
</template>

<script setup lang='ts'>
import { ref, reactive, watch, PropType, nextTick, onMounted } from 'vue'
import deptDialog from "@/components/Dialog.vue"
import type { FormInstance, FormRules } from "element-plus"
import { userList } from "@/api/user"
import { Page } from "@/interface/common"
import { DeptParams } from "@/interface/dept"

const props = defineProps({
    show: {
        type: Boolean,
        default: true,
        required: true
    },
    title: {
        type: String,
        default: '新增菜单',
        required: true
    },
    deptFormData: Object,
    dept: Array,
    type: String,
    parentId: Array
})
let list = ref<any>([])
let deptData = ref<DeptParams>({
    parentId: [""],
    deptName: '',
    user: '',
    userEmail: '',
    userId: '',
    userName: ''
})

// 监听是新增还是编辑
watch(() => props.type, (newValue, oldValue) => {
    let action = newValue ? newValue : 'create'
    console.log(action)
    if (action === 'edit') {
        console.log(1)
        nextTick(() => {
            deptData.value = props.deptFormData as DeptParams
            console.log('打印menuData', deptData.value)
        })
    }
}, { immediate: true })

let userPage = reactive<Page>({
    pageNum: 1,
    pageSize: 10,
    total: 0
})
// 获取用户列表
const getUserList = async () => {
    const res = await userList(userPage)
    console.log('用户列表', res)
    if (userPage.pageNum === 1) {
        list.value = res.list
    } else {
        list.value.push(...res.list as unknown as [])
    }

    userPage = res.page
}
onMounted(() => {
    getUserList()
})

const handleUser = (val: string) => {
    console.log(val)
    const [userId, userName, userEmail] = val.split("/")
    deptData.value = Object.assign({}, deptData.value, { userId, userName, userEmail })
}

// 这是滚动加载
const loadMore = () => {
    if (userPage.pageNum * userPage.pageSize < userPage.total) {
        userPage.pageNum++
        getUserList()
    }
    console.log('数据已经全部加载完毕')
}

// 表单设置
const deptForm = ref<FormInstance>()
const rules = reactive<FormRules>({
    parentId: [{ required: true, message: '请选择上级部门', trigger: 'blur' }],
    deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
    user: [{ required: true, message: '请选择负责人', trigger: 'blur' }]
})

const emits = defineEmits(["close", "submit"])
const close = () => {
    deptForm.value?.resetFields()
    emits("close")
}
const submit = () => {
    deptForm.value?.validate((valid: boolean) => {
        if (valid) {
            const params = Object.assign({}, deptData.value)
            // 删除属性需要是可选的
            delete params.user
            console.log("提交的参数", params)
            emits("submit", params)
            setTimeout(() => {
                close()
            }, 0)
        }
    })
}
</script>
<style lang='scss' scoped>
.el-dialog__header {
    border-bottom: 1px solid red;
}
</style>